package com.kfm.servlet;

import com.kfm.dao.AccountDao;
import com.kfm.model.Account;
import com.kfm.util.MD5Util;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet(value = "/login", initParams = @WebInitParam(name="encode", value="utf-8"))
public class LoginServlet extends HttpServlet {

    private String encode;

    @Override
    public void init() throws ServletException {
        this.encode = getInitParameter("encode");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        request.setCharacterEncoding(encode);

//        String username = request.getParameter("username");
//        String pass = request.getParameter("pass");

        Map<String, String[]> parameterMap = request.getParameterMap();
        Account account = new Account();

        try {
            BeanUtils.populate(account, parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        // 密码做处理
        // 1. Base64 编码
//        Base64.Encoder encoder = Base64.getEncoder();
//
//        byte[] encode = encoder.encode(account.getPass().getBytes(StandardCharsets.UTF_8));
//
//        String s = new String(encode);
//
//        account.setPass(s);
        // 2， md5
        String encode = MD5Util.encode(account.getPass());

        account.setPass(encode);

        // jdbc 连接数据查询
        AccountDao accountDao = new AccountDao();
        Account queryAccount = accountDao.queryAccountByUsernameAndPass(account);

        if (queryAccount == null){
            System.out.println("用户名或密码不正确");
        } else{
            System.out.println("登录成功");
        }


    }
}
